package com.bonorsoft.pay.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.bonorsoft.common.api.Result;
import com.bonorsoft.config.properties.WeixinPayProperties;
import com.bonorsoft.util.DateUtils;
import com.bonorsoft.util.HttpRequest;
import com.bonorsoft.util.IPUtils;
import com.bonorsoft.util.SnowflakeIdWorker;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @description
 * @auth WilliamYe
 * @date 2021/8/31
 * @time 16:29
 */
@RestController
@Log4j2
public class ApiPayController extends ApiBaseController {

    @Autowired
    private WeixinPayProperties weixinPayProperties;

    @GetMapping("/weixinpay")
    public Result<Object> payVip(HttpServletRequest request) {
        //开始支付，创建支付体
        JSONObject json = new JSONObject();
        //生成订单号
        String orderNo = new SnowflakeIdWorker(1, 2).nextId() + "";
        String ip = IPUtils.getIpAddr(request);
        String openid = request.getParameter("openid");
        log.info("1---->openid is value: {},{}", openid, JSONUtil.toJsonStr(weixinPayProperties));
        try {
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put("appid", weixinPayProperties.getAppid()); // 商家平台ID
            paraMap.put("body", weixinPayProperties.getMchname()); // 商家名称-销售商品类目、String(128)
            paraMap.put("mch_id", weixinPayProperties.getMchid()); // 商户ID
            paraMap.put("nonce_str", WXPayUtil.generateNonceStr()); // UUID
            paraMap.put("openid", openid);
            paraMap.put("out_trade_no", orderNo);// 订单号,每次都不同
            paraMap.put("spbill_create_ip", ip);
            paraMap.put("total_fee", "1"); // 支付金额，单位分
            paraMap.put("trade_type", "JSAPI"); // 支付类型
            paraMap.put("notify_url", weixinPayProperties.getNotifyPath());// 此路径是微信服务器调用支付结果通知路径随意写
            String sign = WXPayUtil.generateSignature(paraMap, weixinPayProperties.getAppserct());
            paraMap.put("sign", sign);
            String xml = WXPayUtil.mapToXml(paraMap);
            log.info("xml为：{}" , xml);
            // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
            String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            String xmlStr = HttpRequest.httpsRequest(unifiedorder_url, "POST", xml);
            log.info("xmlStr为：{}" , xmlStr);
            String prepay_id = "";// 预支付id
            if (xmlStr.contains("SUCCESS")) {
                Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
                prepay_id = map.get("prepay_id");
            }

            Map<String, String> payMap = new HashMap<String, String>();
            payMap.put("appId", weixinPayProperties.getAppid());
            payMap.put("timeStamp", DateUtils.getCurrentTimestamp() + "");
            payMap.put("nonceStr", WXPayUtil.generateNonceStr());
            payMap.put("signType", "MD5");
            payMap.put("package", "prepay_id=" + prepay_id);
            String paySign = WXPayUtil.generateSignature(payMap, weixinPayProperties.getAppserct());
            payMap.put("paySign", paySign);
            payMap.put("openid", openid);
            payMap.put("outTradeNo", orderNo);
            return Result.ok(payMap);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("支付失败");
        }


    }
}
